瀑布流布局是一種新的佈局方式,項目可以自動匹配大小適應螢幕。
在RecycleView中,要呈現瀑布流樣式,需要用到StaggeredGridLayoutManager來實作。
先上Acitvity
class StaggeredGridViewActivity : AppCompatActivity() {
lateinit var staggeredGridLayoutManager: StaggeredGridLayoutManager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title="StaggeredGridLayout"
staggeredGridLayoutManager = StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL)
recycleview_main.layoutManager= staggeredGridLayoutManager
val adapter = RVStaggeredGridViewAdapter(this, SwitchData.defaultList)
recycleview_main.adapter = adapter
}
}
StaggeredGridLayoutManager其實跟之前的GridLayoutManager的用法一樣,要宣告spanCount以及方向。
所以對GridLayoutManager熟悉的朋友們在使用StaggeredGridLayoutManager應該沒有困難。
StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL)
Adapter
class RVStaggeredGridViewAdapter(
private val context: Context,
private val dataList: MutableList<SwitchData>
) :
RecyclerView.Adapter<RVStaggeredGridViewAdapter.ViewHolder>() {
var mContext: Context
init {
mContext = context
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
var view = LayoutInflater.from(parent.context).inflate(R.layout.recycleview_gridview_layout, parent, false)
return ViewHolder(view, viewType)
}
override fun getItemCount(): Int {
return dataList.size
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val item = dataList[position]
holder?.bindModel(item)
}
inner class ViewHolder(itemView: View, var viewType: Int) : RecyclerView.ViewHolder(itemView) {
var nameTextView: TextView? = null
var likeTextView: TextView? = null
var commentTextView: TextView? = null
fun bindModel(item: SwitchData) {
var imageView: ImageView? = null
imageView = itemView.findViewById(R.id.iv_small)
nameTextView = itemView.findViewById(R.id.tv_namesmall)
Glide.with(mContext).load(item.image).into(imageView!!)
nameTextView?.setText(item.name)
likeTextView?.setText("Likes: ${item.like}")
commentTextView?.setText("comments: ${item.comment}")
}
}
}
瀑布流的顯示,其實在google的圖片搜尋就是一個最好的例子。
在一些網路型錄中顯示商品時也是常見的顯示方式。
除了有效運用剩餘空間的優點之外,在視覺上也是一種整齊美觀的享受。